#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
except:
    pass
import jarryLibs.mayakit.MayaUtils as mu
reload(mu)
import elsLibs.AssetInfoFromFile as elsaif
reload(elsaif)
import jarryLibs.dict2json as jd2j

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CheckELSRigTpose(CheckBase):
    def __init__(self):
        super(CheckELSRigTpose, self).__init__()
        self.tpose_time = 950
        self.exculde_attrtype_list = ['stretchy', 'Global']

    def get_asset_reference_list(self):
        asset_refs = []
        for ref in pm.listReferences():
            if 'Z:/ELS_Project/Assets/' in ref.path and 'rig' in ref.path and 'Character' in ref.path and ref.isLoaded():
                asset_refs.append(ref)
        return asset_refs

    def check(self):
        result_log = 'Error:'
        ref_list = self.get_asset_reference_list()
        # print ref_list
        globl_error = 0
        for ref_node in ref_list:
            ref_path = ref_node.path
            namespace = ref_node.namespace
            result_log += u'<br><font color=\"#007900\">%s:' % namespace
            error = 0
            error_ctrl = []
            tpose_file = ref_path[0:-3] + '_Tpose.json'
            if os.path.exists(tpose_file):
                ctrl_data = jd2j.dict2json(tpose_file).read()
                for ctrl in ctrl_data:
                    exists_ctrl = namespace + ':' + ctrl

                    key_data = ctrl_data[ctrl]
                    for key in key_data:
                        if key in self.exculde_attrtype_list:
                            continue
                        value = key_data[key]
                        exists_key = exists_ctrl + '.' + key
                        exists_value = float(cmds.getAttr(exists_key, time=self.tpose_time))
                        # print exists_ctrl, value, exists_value
                        if 'e-' in str(exists_value):
                            # 排除maya的bug
                            continue
                        if str(value) != str(exists_value):
                            # print exists_ctrl
                            error += 1
                            result_log += u'<br>%s未匹配Tpose参数 %s->%s;' % (exists_key, exists_value, value)
                            result_log = result_log.replace('007900', 'FF0000')
                            error_ctrl.append(exists_ctrl)
            else:
                error = 999
                result_log += u'%s:找不到Tpose预设文件' % tpose_file
                result_log = result_log.replace('007900', 'FF0000')

            if error == 0:
                result_log += u'没有问题;'
            else:
                globl_error += error
                if error != 999:
                    result_log += u'<br>出错的控制器:%s' % error_ctrl
        if globl_error == 0:
            result_log = result_log.replace('Error:', 'Succeed:')
        return result_log

    def fix(self):
        result_log = 'Succeed:'
        ref_list = self.get_asset_reference_list()
        for ref_node in ref_list:
            ref_path = ref_node.path
            namespace = ref_node.namespace
            result_log += u'<br><font color=\"#007900\">%s:' % namespace
            error = 0
            # error_ctrl = []
            tpose_file = ref_path[0:-3] + '_Tpose.json'
            if os.path.exists(tpose_file):
                ctrl_data = jd2j.dict2json(tpose_file).read()
                for ctrl in ctrl_data:
                    exists_ctrl = namespace + ':' + ctrl

                    key_data = ctrl_data[ctrl]
                    for key in key_data:
                        if key in self.exculde_attrtype_list:
                            continue
                        value = key_data[key]
                        exists_key = exists_ctrl + '.' + key
                        exists_value = float(cmds.getAttr(exists_key, time=self.tpose_time))
                        if 'e-' in str(exists_value):
                            # 排除maya的bug
                            continue
                        if str(value) != str(exists_value):
                            # cmds.setAttr(exists_value)
                            try:
                                cmds.setKeyframe(exists_key, v=value, t=self.tpose_time)
                                result_log += u'<br>%s 已经在%s帧设置参数: %s->%s;' % (exists_key, self.tpose_time,exists_value, value)
                            except:
                                error += 1
                                result_log += u'<br>%s 设置失败,请检查控制器是否锁住: %s->%s;' % (exists_key, self.tpose_time,exists_value, value)
                                result_log = result_log.replace('007900', 'FF0000').replace('Succeed:', 'Error:')
                            # error_ctrl.append(exists_ctrl)
            else:
                result_log += u'%s:找不到Tpose预设文件' % tpose_file
                result_log = result_log.replace('007900', 'FF0000')
        return result_log
